import { __CONFIG__ } from '@/common'
import SparkMD5 from 'spark-md5'
import { UUID } from '.'
const { hashType = 'md5' } = __CONFIG__ || {}
/**
 *
 * @from https://github.com/satazor/js-spark-md5
 */
export const hashFile = (file: Blob, { chunkSize, onanalyse } = {
  chunkSize: 1024 * 1024,
  onanalyse: (loaded: number, total: number) => {}
}) => {
  if (hashType === 'uuid') return Promise.resolve(UUID())
  const chunks = Math.ceil(file.size / chunkSize)
  let currentChunk  = 0
  const spark = new SparkMD5.ArrayBuffer()
  const fileReader = new FileReader()
  return new Promise<string>(function (resolve, reject) {
    fileReader.addEventListener('load', function () {
      const chunk = fileReader.result as ArrayBuffer
      spark.append(chunk)
      currentChunk++
      if (currentChunk < chunks) {
        loadNext();
      } else {
        resolve(spark.end())
      }
    })
    fileReader.addEventListener('error', reject)
    function loadNext() {
      const start = currentChunk * chunkSize
      const end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize
      onanalyse?.(end, file.size)
      fileReader.readAsArrayBuffer(file.slice(start, end));
    }
    loadNext()
  })
}
